#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/**
 * 
 *  lseek函数驱动实现，操作驱动中一个字符串，可以当做file来理解
 执行结果： 
 off is 13
off is 0
read is hello world 
off is 13
off is 12
off is 18
off is 0
read is hello world Linux
off is 19
 */

int main(int argc,char *argv[]){
	int fd;//定义int类型文件描述符
	unsigned int off=0;//定义读写偏移位置
	//char readbuf[13] = {0};//定义读取缓冲区readbuf
	//char readbuf1[19] = {0};//定义读取缓冲区readbuf1

	fd = open("/dev/test",O_RDWR,666);//打开/dev/test设备
	if(fd < 0 ){
		printf("file open error \n");
	}
	write(fd,"hello world ",13);//向fd写入数据hello world
	off = lseek(fd,0,SEEK_CUR);//读取当前位置的偏移量 写入13以后返回13
	printf("off is %d\n",off); //ret =13 

    	off = lseek(fd,0,SEEK_SET);//将偏移量设置为0 ，把文件读写指针设置到开头
    	printf("off is %d\n",off);  // 0  指针距离开头位置0 
		

	char readbuf[13] = {0};//定义读取缓冲区readbuf
	read(fd,readbuf,sizeof(readbuf));//将写入的数据读取到readbuf缓冲区
	printf("read is %s\n",readbuf);

    	off = lseek(fd,0,SEEK_CUR);//读取当前位置的偏移量
    	printf("off is %d\n",off);   //off is 13

		//必须，上面13把\0写入了，这里把\0去掉，否则后面Linux写入前面多了一个\0,读取不出
	off = lseek(fd,-1,SEEK_CUR);//将当前位置的偏移量向前挪动一位
	printf("off is %d\n",off);   //off is 12 

    	write(fd,"Linux",6);//向fd写入数据Linux
    	off = lseek(fd,0,SEEK_CUR);//读取当前位置的偏移量
   	 printf("off is %d\n",off);   //off is 18

    	off = lseek(fd,0,SEEK_SET);//将偏移量设置为0
    	printf("off is %d\n",off);

    	char readbuf1[19] = {0};//定义读取缓冲区readbuf1
	read(fd,readbuf1,sizeof(readbuf1));//将写入的数据读取到readbuf1缓冲区
    	printf("read is %s\n",readbuf1);  

    	off = lseek(fd,0,SEEK_CUR);//读取当前位置的偏移量
    	printf("off is %d\n",off);  //  off is 19
	close(fd);
	return 0;
}
